<?php
// $Id$

/**
 * Controller_Vote 控制器
 */
class Controller_Vote extends Controller_Abstract
{
    function getEnterpriseAuditStatus($user)
    {
        $enterprise_setting = Enterprisesetting::find('enterprise_id = ?', $user->enterprise_id)->getOne();
        return $enterprise_setting->audit_open_or_not;
    }

    function actionRejectIndex()
    {
        if(null == $this->_app->currentUserObject())
        {
            return $this->_redirect(url('default/index'));
        }
        $current_user = $this->_app->currentUserObject();
        $votes = Vote::find('enterprise_id = ? and vote_status = 5', 
            $current_user->user_id)->order('vote_create_time_stamp desc');
        $page = intval($this->_context->page);
        $page = ($page < 1) ? 1 : $page;
        $votes->limitPage($page, 10);
        $this->_view['pagination'] = $votes->getPagination();

        $reject_count = count($votes->getAll());
        $this->_view['permission_id'] = $current_user->permission_id;
        $this->_view['votes'] = $votes->getAll();
        $this->_view['reject_count'] = $reject_count;
        $this->_viewname = 'rejectindex';
    }

    function actionIndex()
    {
        if(null == $this->_app->currentUserObject())
        {
            return $this->_redirect(url('default/index'));
        }
        $current_user = $this->_app->currentUserObject();
        $enterprise_audit_status = $this->getEnterpriseAuditStatus($current_user);
        if($current_user->permission_id == 3)
        {
            $select = Vote::find("enterprise_id = ? and vote_status = ?", $current_user->enterprise_id, '1');
            $this->_view['audit_count'] = $select->getCount();
            $select = Vote::find("enterprise_id = ? and vote_status = ?", 
                $current_user->enterprise_id, '1')->order('vote_create_time_stamp desc');
        }
        else
        {
            $select = Vote::find("enterprise_id = ? and vote_status = ?", $current_user->enterprise_id, '5');
            $this->_view['reject_count'] = $select->getCount();
            $select = Vote::find("enterprise_id = ?", $current_user->enterprise_id)->order('vote_create_time_stamp desc');
        }
        //dump($select->__toString());
        $page = intval($this->_context->page);
        $page = ($page < 1) ? 1 : $page;
        $vote_per_page = 10;
        $select->limitPage($page, $vote_per_page);
        $this->_view['pagination'] = $select->getPagination();

        $this->_view['enterprise_audit_status'] = $enterprise_audit_status;
        $this->_view['votes'] = $select->getAll();
        $this->_view['permission_id'] = $current_user->permission_id;
        $this->_view['num'] = ($select->getCount() > $vote_per_page) ? $vote_per_page : $select->getCount();
        $this->_viewname = 'Index';
    }

    function dump2StaticHtml($vote_id, $vote_name, $vote_content, $vote_options, $isMulti)
    {
        $file_dir = $this->_app->config('ROOT_DIR').'/static/vote/'.date('Ym');
        $url_path = $this->_context->baseDir().'static/vote/'.date('Ym');

        if(!file_exists($file_dir))
        {
            mkdir($file_dir, 0777);
        }
        $file_name = $file_dir.'/'.$vote_id.'.html';

        $html_file_fp = fopen($file_name, 'w');
        $header_str=
"<!DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Transitional//EN http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>
<html>
<head>
<meta http-equiv=\"Content-type\" content=\"text/html; charset=utf-8\" /></head><body>\n";

        $html_header = $header_str."<h1>$vote_name</h1>\n";
        $web_site=Q::ini('appini/web_site_ip');
        $options = "\n<form action=\"http://".$web_site. $this->_context->baseDir() . "tianyi/index.php?controller=vote&action=Count\" method=\"post\" id=\"mainform\" name=\"mainform\" enctype=\"multipart/form-data\" >\n";
        $type = '"radio"';
        //dump($isMulti);
        if($isMulti == 1)
        {
            $type = '"checkbox"';
        }
        foreach($vote_options as $option)
        {
            $element = "<input type=".$type. " value=".$option->option_id." name='vote'/>".$option->option_content."<br/>\n";
            $options .= $element;
        }
        $options .="<input type=\"hidden\" value=\"".$vote_id."\" name=\"vote_id\" />\n";
        $options .="<input type=\"submit\" value=\"提交\"/>\n</form>\n";

        $html_tail = "\n</body>\n</html>";
        fwrite($html_file_fp, $html_header.$vote_content.$options.$html_tail);
        fclose($html_file_fp);

        return $url_path.'/'.$vote_id.'.html';
    }

    function actionCount()
    {
        if(isset($_POST))
        {
            //get variable from post form
            $username = $_POST['username'];
            $voteid = $_POST['voteid'];
            $optionids = $_POST['optionid'];

            $user = User::find("username = $username")->getOne();
            $vote = Vote::find("vote_id = $voteid")->getOne();
            $options_array = split('[,]', $optionids);
            //dump($user->user_id . "\n");
            //dump($vote->vote_id . "\n");
            //dump($optionids);
            //dump($options_array);
            if(strlen($optionids) == 0 || count($options_array) == 0)
            {
                echo "failed";
                return;
            }

            //$result = Uservote::find("user_id = ? and vote_id = ?", $user->user_id, $vote->vote_id)->getAll();

            //if(count($result) > 0)
            //{
            //    echo "failed";
            //    return;
            //}

            $options = Options::find("option_id in (?)", $optionids)->getAll();
            //dump($options);
            
            $sql = "select * from tianyi_options where option_id in ($optionids); ";
            //dump($sql);
            $dbcon=QDB::getConn();
            $handle =$dbcon->execute($sql);
            $options = $handle->fetchAll();

            //dump($options);
            if(count($options) == 0)
            {
                echo "failed";
                return;
            }

            //dump($options);

            $dbcon=QDB::getConn();
            for($i = 0; $i< count($options); )
            {
                //dump($options[$i]);
                $option = $options[$i];
                $user_vote = new Uservote();
                $user_vote->option_id = $option['option_id'];
                $user_vote->vote_id = $vote->vote_id;
                $user_vote->user_id = $user->user_id;
                $user_vote->save();
                $option_count = $option['option_count'] + 1;
                $option_id = $option['option_id'];

                $sql = "update tianyi_options set option_count = $option_count where option_id = $option_id  ";
                $handle =$dbcon->execute($sql);
                $i = $i + 1;
                //dump($i);
            }
            echo "success";
            return;

        }
        else
        {
            //dump($_POST);
            echo "failed";
            return;
        }
    }

    function actionShowResult()
    {
        $currnet_user = $this->_app->currentUserObject();
        $vote_id = $this->_context->vote_id;
        $vote = $this->_context->vote;
        $option_id = $this->_context->vote_option_id;
        $vote = Vote::find('vote_id = ?', $vote_id)->getOne();
        $options = Options::find('vote_id = ?', $vote->vote_id)->getAll();
        $total_count = 0;
        foreach($options as $option)
        {
            $total_count += $option->option_count;
        }
        $this->_view['vote'] = $vote;
        $this->_view['options'] = $options;
        $this->_view['total_count'] = $total_count;
        $this->_viewname = 'ShowResult';
    }

    function actionAdd()
    {
        $current_user = $this->_app->currentUserObject();
        require '_code/lib/constant.php';
        $upload_dir = $this->_context->baseDir() . PREFIX_UPLOAD_ENTERPRISE . "/$current_user->enterprise_id";
        $this->_view['upload_dir'] = $upload_dir;
        if($this->_context->isPost())
        {
            try
            {
                //dump($_POST);
                $vote = new Vote();
                require '_code/lib/utils.php';
                $vote->vote_name = trim_str($_POST['vote_topic']);
                $vote->vote_content = $_POST['content'];
                $vote->vote_type = 0;
                if($_POST['multi_check'] == "on")
                {
                    $vote->vote_type = 1;
                }

                $vote->vote_summary = trim_str($_POST['summary']);
                //dump($vote);
                $_BASE_DIR = $this->_context->baseDir();
                $web_site=Q::ini('appini/web_site_ip');
                $default_logo = $web_site.$_BASE_DIR . 'static/const_img/default.png';
                $vote->vote_icon = isset($_POST['uploadpic']) ?  ($web_site . $_POST['uploadpic']) : $default_logo; 
                $vote->enterprise_id = $current_user->enterprise_id;
                $vote->vote_create_userid = $current_user->user_id;
                $vote->vote_audit_userid = $current_user->user_id;
                $vote->vote_create_time_stamp = time();
                $vote->vote_audit_time_stamp = 0;
                $vote->vote_status = 1;
                if(!$this->getEnterpriseAuditStatus($current_user))
                {
                    $vote->vote_status = 4;
                }
                $vote->save();
                $options = array();

                foreach($_POST as $key => $value)
                {
                    //dump(strpos($key, 'option') === 0);
                    if (strpos($key, 'option') === 0)
                    {
                        $option = new Options();
                        $option->option_content = $value;
                        $option->vote_id = $vote->vote_id;
                        $option->save();
                        array_push($options, $option);
                    }
                } 
                $isMulti = $vote->vote_type;
                $file_path = $this->dump2StaticHtml($vote->vote_id,
                    $vote->vote_name,
                    $vote->vote_content,
                    $options,
                    $isMulti);
                $vote->vote_url = $vote->vote_id;
                $vote->save();
            }
            catch (Exception $ex)
            {   
                return $this->_redirectMessage(
                    '发布投票出错',
                    dump($ex),
                    url('vote/Index'));
            }
            return $this->_redirectMessage(
                '提示',
                '发布投票成功',
                url('vote/Index'));
        }

    }

    function actionEdit()
    {
        $current_user = $this->_app->currentUserObject();
        $vote_id = $this->_context->vote_id;
        
        require '_code/lib/constant.php';
        $upload_dir = $this->_context->baseDir() . PREFIX_UPLOAD_ENTERPRISE . "/$enterprise->enterprise_id";

        $vote = Vote::find('vote_id = ?', $vote_id)->getOne();
        $vote_options = Options::find('vote_id = ?', $vote_id)->getall();
        if(!$_POST)
        {
            $this->_viewname = 'Edit';
            $this->_view['upload_dir'] = $upload_dir;
            $this->_view['vote'] = $vote;
            $this->_view['options'] = $vote_options;
            return;
        }
        else
        {
            require '_code/lib/utils.php';
            $vote->vote_name = trim_str($_POST['vote_name']);
            $vote->vote_content = $_POST['content'];
            $vote->vote_summary = trim_str($_POST['summary']);
                //dump($vote);
            $_BASE_DIR = $this->_context->baseDir();
            $web_site=Q::ini('appini/web_site_ip');
            $default_logo = $web_site.$_BASE_DIR . 'static/const_img/default.png';
            $vote->vote_icon = isset($_POST['uploadpic']) ?  ($web_site . $_POST['uploadpic']) : $default_logo; 
            $file_path = $this->dump2StaticHtml($vote->vote_id,
                $vote->vote_name,
                $vote->vote_content,
                $options,
                $isMulti);
            //$vote->vote_url = url('vote/RequireID', array('voteid' => $vote->vote_id));
            $vote->vote_url = $vote->vote_id;
            $vote->vote_status = 1;
            if(!$this->getEnterpriseAuditStatus($current_user))
            {
                $vote->vote_status = 4;
            }
            $vote->save();
            //$vote->vote_type = isset($_POST['multi_check']) ?  1 : 0;
            //Options::meta()->destroywhere('vote_id = ?', $vote_id);	
            //foreach($_POST as $key => $value)
            //{
            //    //dump(strpos($key, 'option') === 0);
            //    if (strpos($key, 'option') === 0)
            //    {
            //        $option = new Options();
            //        $option->option_content = $value;
            //        $option->vote_id = $vote->vote_id;
            //        $option->save();
            //    }
            //} 

            $vote->save();
            return $this->_redirectmessage(
                '编辑投票',
                '投票编辑成功',
                url('vote/Index'));
        }
    }

    function actionRequireID()
    {
        $dbcon=QDB::getConn();
        $voteid = $this->_context->vote_id;
        $username = $this->_context->user_name;
        $user = User::find("username = ?", $username)->getOne();
        $vote = Vote::find("vote_id = ?", $voteid)->getOne();

        $sql = "select *  from tianyi_users_votes where user_id = $user->user_id and vote_id = $voteid; ";
        //dump($sql);
        $handle =$dbcon->execute($sql);
        $select = $handle->fetchAll();

        $count = count($select);
        //dump($count);
        $isvoted = "false";
        if($count > 0)
        {
            $isvoted = "true";
            if($user->enterprise_id == '41')
            {
                $isvoted = "false";
            }
        }
        $options = Options::find("vote_id = $voteid")->getAll();
        $vote_summary = "";
        if($vote->vote_summary)
        {
            $vote_summary = $vote->vote_summary ;
        }
        $xml_str = 
"<?xml version=\"1.0\" encoding=\"utf-8\"?>
<root>
    <item>
        <vote id=\"$voteid\" icon=\"$vote->vote_icon\" title=\"$vote->vote_name\" type=\"$vote->vote_type\" summary=\"$vote_summary\" isvoted=\"$isvoted\" />\n";
        foreach($options as $option)
        {
            $xml_str .= "        <option id=\"$option->option_id\" title=\"$option->option_content\" count=\"$option->option_count\" />\n";
        }

        $xml_str .= "    </item>\n</root>\n";
        
        echo $xml_str;
        return;
    }

    function actionRequire()
    {
        require 'genrss.php';
        $username=$this->_context->user_name;
        $user = User::find('username= ?', $username)->getOne();
        //dump($user);
        $current_user = $this->_app->currentUserObject();
        $select = Vote::find('enterprise_id = ? and vote_status = 4', $user->enterprise_id)->all();
        $page = intval($this->_context->page);

        if($page < 1) 
        {
            $page = 1;
        }
        $select->limitPage($page, Q::ini('appini/web_page_count'));
        $votes = $select->getAll();
        $date = Date('Y-m-d H:i:s', time());
        $web_site = Q::ini('appini/web_site_ip');
        $rss_gen = new RSS('投票', 'http://baidu.com', '测试','http://baidu.com');
        foreach($votes as $vote)
        {
            $rss_gen->AddItem($vote->vote_name, $vote->vote_url, $vote->vote_summary, $vote->vote_create_time_stamp, $vote->vote_icon);

        }
        $ret=$rss_gen->Fetch();
        echo $ret;
        return;
    }

    function actionPreview()
    {
        $vote_id = $this->_context->vote_id;
        $vote = Vote::find('vote_id = ?', $vote_id)->getOne();
        $options = Options::find('vote_id = ?', $vote_id)->getAll();
        $creator = User::find('user_id = ?', $vote->vote_create_userid)->getOne()->username;
        $this->_view['vote'] = $vote;
        $this->_view['creator'] = $creator;
        $this->_view['options'] = $options;
        $this->_viewname = "htmlview";
    }

    function actionAudit()
    {
        $vote_id = $_POST['vote_id'];
        $vote = Vote::find('vote_id = ?', $vote_id)->getOne();
        $current_user = $this->_app->currentUserObject();

        if(isset($_POST['result']))
        {
            //dump($_POST);
            if($_POST['result'] == 'pass')
            {
                $vote->vote_audit_userid = $current_user->user_id;
                $vote->vote_audit_time_stamp = time();
                $vote->vote_status = 4;
            }
            else
            {
                $vote->vote_status = 5;
                $vote->vote_reject_reason = $_POST['reason'];
            }
            $vote->save();
            return $this->_redirectMessage('投票审核',
                '投票已经成功审核',
                url('vote/index'));
        }
    }

    function actionRemove()
    {
        if(isset($_POST['checkboxname']))
        {
            $vote_id_array = $_POST['checkboxname'];
            //dump($vote_id_array);
            $id_array_string = join(",", $vote_id_array);
            $sql = "delete from tianyi_votes where vote_id in ( " . $id_array_string . " )";
            //dump($sql);
            $dbconn = QDB::getConn();
            $dbconn->execute($sql);
        }
        return $this->_redirectMessage(
            '投票删除',
            '投票已经成功被删除',
            url('vote/Index'));
    }
}

?>

